<?php
/**
 * Created by PhpStorm.
 * User: liyu
 * Date: 2018/4/26
 * Time: 上午10:16
 */

namespace app\api\service;


use app\api\model\Org as OrgModel;

class OrgService extends Base
{
    public function create($guid,$data)
    {
        $where = [
            'name' => $data['name']
        ];
        $OrgInfo = $this->getInfo($where,['name']);
        //添加检查
        if (!is_null($OrgInfo))
            set_error_exception('org_name_exists');
        //检查结束
        $row = OrgModel::addInfo($guid,$data)->id;
        $result = $this->dbOperationResult($row);
        return $result;
    }

    public function getInfo($where,$field=true)
    {
        $infoObj = OrgModel::getInfo($where,$field);
        is_null($infoObj) ? : $infoObj = $infoObj->toArray();
        return $infoObj;
    }

    public function update($guid,$where,$data)
    {
        //数据不为空检查
        $field = $this->checkParamIsNull($data);

        $odata = $this->getInfo($where,$field);
        //数据不存在检查
        if (empty($odata)) {
            set_error_exception('data_not_exists');
        }
        //数据无修改检查
        foreach ($data as $k => $v) {
            if ($v === $odata[$k]) {
                set_error_exception('error',['code'=>10001,'msg'=>$k.'无修改']);
            }
        }
        //数据唯一检查
        $unqiue = ['name'];
        foreach ($unqiue as $k => $v) {
            if (isset($data[$v])) {
                $map = [
                    $v => $data[$v]
                ];
                if(!empty($this->getInfo($map,['id'])))
                    set_error_exception('error',['code'=>10001,'msg'=>$v.'重复']);
            }
        }

        $row = OrgModel::updateInfo($guid,$odata,$data,$where);
        $result = $this->dbOperationResult($row);
        return $result;
    }

    public function getOrgInfoListByMap($where)
    {
        $result = $result1 = [];
        $obj = OrgModel::getInfoList($where,['id','name','parent_id']);
        foreach ($obj as $k => $v) {
            $result[] = $v->toArray();
        }
        $result1 = $this->getTree($result,0);
        return $result1;
    }

    public function getTree($data, $pId)
    {
        $tree = [];
        foreach($data as $k => $v)
        {
            if($v['parent_id'] == $pId)
            {        //父亲找到儿子
                $v['list'] = $this->getTree($data, $v['id']);
                $tree[] = $v;
            }
        }
        return $tree;
    }
}